package com.mall.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.mall.domain.Order;
import com.mall.domain.Product;
import com.mall.domain.enums.BizCodeMessage;
import com.mall.domain.exception.BizException;
import com.mall.domain.exception.OpenBizException;
import com.mall.order.service.OrderService;
import com.mall.order.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author chenlufeng
 * @date 2022/2/23
 */
@RestController
@Slf4j
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ProductService productService;

    //下单--fegin
    @RequestMapping("/order/prod/22/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info(">>客户下单，这时候要调用商品微服务查询商品信息");

        //从nacos中获取服务地址
//        ServiceInstance serviceInstance = discoveryClient.getInstances("service-product").get(0);
//        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("service-product");
//        int index = new Random().nextInt(serviceInstanceList.size());
//
//        ServiceInstance serviceInstance = serviceInstanceList.get(index);
//
//        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
//        log.info(">>从nacos中获取到的微服务地址为:" + url);

        //直接使用微服务名字, 从nacos中获取服务地址
//        String url = "service-product";
//        Product product = restTemplate.getForObject("http://" + url + "/product/" + pid, Product.class);

        //使用feign 调用
        Product product = productService.findByPid(pid);
        log.info(">>商品信息,查询结果:" + JSON.toJSONString(product));
        Order order = new Order();
//        order.setUid(1);
//        order.setUsername("测试用户");
//        order.setPid(product.getPid());
//
//        order.setPname(product.getPname());
//        order.setPprice(product.getPprice());
//        order.setNumber(1);
//        orderService.save(order);
        order.setPname(product.getPname());
        if (0 == 0) throw new RuntimeException("ddddd");
        return order;
    }

//    public String blockHandles(BlockException e) {
//        log.error("触发blockexception{}", e.getCause());
//        return "被流控啦";
//    }

    @SentinelResource(value = "message")
    @GetMapping("/test")
    public String test3() {
        return "hh";
    }

    // 限流规则
    @PostConstruct
    private void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule("message");
        // set limit qps to 20
        rule.setCount(2);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setLimitApp("default");
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

//    @PostConstruct
    private void initDegradeRule() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource("message");
        // set threshold RT, 10 ms
        rule.setCount(0.01);
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        rule.setTimeWindow(10);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }
}
